#include "recbox.h"
#include "ui_recbox.h"

#include "recboxitem.h"
#include <QJsonObject>
#include <QPushButton>
#include <QDebug>

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(2),
    col(10)
{
    ui->setupUi(this);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int r)
{
    if (1 == r)
    {
        this->row = r;
        this->col /= 2;
        ui->recListDown->hide();
    }

    imageList = data;

    currentIndex = 0;
    count = imageList.size() / col;

    // 在RecBox控件中添加RecBoxItem
    createRecBoxItrm();
}

void RecBox::createRecBoxItrm()
{
    // 删除RecBox内部之前的元素
    QList<RecBoxItem*> recUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for (auto item : recUpList)
    {
        ui->recListUpHLayout->removeWidget(item);
        delete item;
    }

    QList<RecBoxItem*> recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for (auto item : recDownList)
    {
        ui->recListDownHLayout->removeWidget(item);
        delete item;
    }

    // 创建RecBoxItem对象，添加到RecBox中
    for (int i = currentIndex * col; i < col + currentIndex * col; ++i)
    {
        RecBoxItem* item = new RecBoxItem(this);

        // 设置文本和图片
        QJsonObject obj = imageList[i].toObject();
        item->setRecText(obj.value("text").toString());
        item->setRecImage(obj.value("path").toString());

        if (2 == row && i >= col / 2 + currentIndex * col) ui->recListDownHLayout->addWidget(item);
        else ui->recListUpHLayout->addWidget(item);
    }
}

void RecBox::on_btUp_clicked()
{
    // 点击之后，需要显示前一组图片，如果已经是第0组图片了，就显示最后一组
    currentIndex = (currentIndex + count - 1) % count;

    createRecBoxItrm();
}

void RecBox::on_btDown_clicked()
{
    // 点击之后，需要显示下一组图片，如果已经是最后一组图片，就显示第0组
    currentIndex++;
    currentIndex %= count;

    createRecBoxItrm();
}
